<?php
/**
 * Add by zhao.huang 20170801
 * 功能：处理商品品牌业务相关内容
 * 
 * 修改时间：2018/1/26
 * 修改人：lizenan
 * 修改功能：【后台需求】品牌管理关键词维护修改
 * 任务ID：484
 */
namespace backend\controllers;
use Yii;
use yii\web\AdminController;
use backend\models\UploadForm;
use backend\models\GoodsBrand;
use backend\models\GoodsCategoryBr;
use backend\models\GoodsBrandDetail;
use backend\models\GoodsCategoryBrGroup;
use common\helps\tools;
use backend\models\GoodsKeyword;
use backend\models\GoodsSaleEdit;

class GoodsBrandController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'GoodsBrand';


    /**
     * 导航相关修改时清空导航redis缓存
     * action 方法名
     */
    public function beforeAction($action){

        $currentaction = $action->id;

        $novalidactions = ['change-brand-useflg','brand-save','disable-brand','enable-brand',
        'update-cate-br-group','add-cate-br-group'];

        if(in_array($currentaction,$novalidactions)){

            \common\helps\tools::delWebNavRedis();

        }
        parent::beforeAction($action);

        return true;
    }

    /**
     * @return string
     * 品牌管理首页
     */
    public function actionList(){
        $query = GoodsBrand::find()->select(['tag'])->distinct()->all();
        $this->saveLog($this->service,'品牌管理页','VIEW','');                     //日志
        //关键字
        $keyword = GoodsKeyword::find()->select('name')->where('use_flg=1')->orderBy('sort asc')->asArray()->all();
        $model = new UploadForm();
        return $this->render('list',['tag'=> $query,'model'=>$model,'keyword'=>$keyword]);
    }

    /**
     * 取得单个品牌信息
     */
    public function actionBrandView(){
        try{
            $data = Yii::$app->request->post();

            if(empty($data['id']) || $data['id'] ==''){
                $this->retJson('参数错误！',9003);
            }
            $result = GoodsBrand::findOne(array('id'=>$data['id']));
            $this->retJson(\yii\helpers\Json::encode($result),200);

        }catch(\Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson('系统异常',9003);
        }
    }
    /**
     * 取得品牌信息
     */
    public function actionGetBrandList(){
        try{
            $data = Yii::$app->request->post();
            $condition = array();
            $condition[] = 'and';
            //品牌名称条件
            if(!empty($data['brand_name'])){
                $condition[] = ['like', 'brand_name', $data['brand_name']];
            }

            //标签
            if(!empty($data['tag']) || $data['tag'] !=''){
                $condition[] = ['tag' => $data['tag']];
            }

            $query = GoodsBrand::find()->where($condition);
            $count = $query->count();

            $list = $query->offset($data['start'])->limit($data['length'])
                ->orderBy(array('id'=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->asArray()->all();

            if(empty($list)){
                $list = array();
            }

            foreach ($list as &$value) {
                $value['brand_desc'] = mb_substr($value['brand_desc'] , 0 , 20,'utf-8');
            }

            //相关参数   http://datatables.club/manual/server-side.html
            $result['draw'] = intval($data['draw']);
            $result['recordsTotal'] = intval($count);
            $result['recordsFiltered'] = intval($count);
            $result['data'] = $list;
            return \yii\helpers\Json::encode($result);

        }catch(\Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            throw new \Exception('操作失败');
            //$this->retJson('系统异常',9003);
        }
    }

    /**
     * 品牌启用禁用处理
     */
    public function actionChangeBrandUseflg(){

        $model = new GoodsBrand();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = $data['useFlg'];
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id = :id",array('id' => $data['id']));

        if($data['useFlg'] == 1){
            $retMsg = '启用';
            $use_flg_type = 'USEFLG1';
        }else{
            $retMsg = '禁用';
            $use_flg_type = 'USEFLG0';
        }
        if($res > 0){
            $this->saveLog($this->service,'品牌' . $retMsg,$use_flg_type,'ID = '.$data['id']);                     //日志
            $this->retJson('品牌' . $retMsg . '成功',200);
        }else{
            $this->retJson('品牌' . $retMsg . '失败',500);
        }
    }

    /**
     * 取得最新TAG数据
     */
    public function actionGetBrandTaglist(){

        $query = GoodsBrand::find()->select(['tag'])->distinct()->asArray()->all();
        return $this->retJson($query,200);
    }

    /**
     * 添加品牌数据
     */
    public function actionBrandSave(){
        $model = new GoodsBrand();
        $data = Yii::$app->request->post();
        $data_now['brand_name'] = trim($data['brand_name']);
        $data_now['brand_desc'] = trim($data['brand_desc']);
        $data_now['use_flg'] = $data['use_flg'];
        $result = GoodsBrand::findOne(array('brand_name'=> $data_now['brand_name']));
        if($data['current_mode'] == 'MOD'){
            //check 是否已存在同样的数据*****************************************************
            if($result){
                if($result['id'] != $data['brand_id']){
                    $this->retJson('品牌名称重复',500);
                }
            }
            $data_now['edit_time'] = date('Y-m-d H:i:s',time());
            $data_now['editor'] = $model->getCreator();
            //check 是否已存在同样的数据*****************************************************
            //更新处理
            $res = $model::updateAll($data_now, "id=:id",array('id'=> $data['brand_id']));
        }else{
            //check 是否已存在同样的数据*****************************************************
            if($result){
                $this->retJson('品牌名称重复',500);
            }
            $data_now['create_time'] = date('Y-m-d H:i:s',time());
            $data_now['creator'] = $model->getCreator();
            //check 是否已存在同样的数据*****************************************************
            //新增处理
            $res = Yii::$app->db->createCommand()->insert('j_goods_brand',$data_now)->execute();
        }

        if($res > 0){
            //后台操作日志
            $this->saveLog($this->service,'品牌保存',$data['current_mode'],'品牌名称：' . $data_now['brand_name'] . "\r\n" . \yii\helpers\Json::encode($data_now));
            $this->retJson('处理成功',200);
        }else{
            $this->retJson('处理失败',500);
        }

    }

    /**
     * @return string
     * 品牌专题维护首页
     */
    public function actionDetail(){
        $data = Yii::$app->request->get();
        $result = GoodsBrand::findOne(array('id'=>$data['id']));
        $this->saveLog($this->service,'品牌专题维护页','VIEW','');                     //日志
        $model = new UploadForm();
        return $this->render('detail',
                             ['model'=> $model ,
                              'brand_name'=> $result['brand_name'],
                              'brand_id'=> $data['id']]
        );

    }

    /**
     * 取得品牌专题数据
     */
    public function actionGetDetailList(){
        try{
            $data = Yii::$app->request->post();
            $condition = array();
            $condition[] = 'and';

            //error_log(print_r($data,1));
            //品牌ID
            if(!empty($data['search_brand_id'])){
                $condition[] = ['brand_id' => $data['search_brand_id']];
            }

            //类型
            if(!empty($data['search_typ'])){
                $condition[] = ['typ' => $data['search_typ']];
            }

            $query = GoodsBrandDetail::find()->where($condition);
            $count = $query->count();
            //取出排序字段
            $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
            $list = $query->offset($data['start'])->limit($data['length'])
                ->orderBy(array("$sort_string"=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->asArray()->all();

            if(empty($list)){
                $list = array();
            }

            //相关参数   http://datatables.club/manual/server-side.html
            $result['draw'] = intval($data['draw']);
            $result['recordsTotal'] = intval($count);
            $result['recordsFiltered'] = intval($count);
            $result['data'] = $list;
            return \yii\helpers\Json::encode($result);

        }catch(\Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            throw new \Exception('操作失败');
        }
    }

    /**
     * 品牌启用禁用处理
     */
    public function actionChangeDetailUseflg(){

        $model = new GoodsBrandDetail();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = $data['useFlg'];
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());
        $res = $model::updateAll($mod_data, "id = :id",array('id' => $data['id']));
        if($data['useFlg'] == 1){
            $retMsg = '启用';
            $use_flg_type = 'USEFLG1';
        }else{
            $retMsg = '禁用';
            $use_flg_type = 'USEFLG0';
        }
        if($res > 0){
            //后台操作日志
            $this->saveLog($this->service,'品牌专题' . $retMsg , $use_flg_type  , 'ID = '.$data['id']);
            $this->retJson('品牌' . $retMsg . '成功',200);
        }else{
            $this->retJson('品牌' . $retMsg . '失败',500);
        }
    }


    /**
     * 保存品牌专题数据
     */
    public function actionSaveDetail(){
        $model = new GoodsBrandDetail();
        $data = Yii::$app->request->post();

        $data_now['brand_id'] = $data['brand_id'];
        $data_now['brand_name'] = $data['brand_name'];
        $data_now['typ'] = $data['typ'];
        $data_now['img'] = $data['img_url_brand'];
        $data_now['img_link'] = $data['img_link'];
        $data_now['img_alt'] = $data['img_alt'];
        $data_now['brand_desc'] = trim($data['brand_desc']);
        $data_now['sort'] = $data['sort'];
        $data_now['use_flg'] = $data['use_flg'];

        $data_now['create_time'] = date('Y-m-d H:i:s',time());
        $data_now['creator'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        //error_log(print_r($data,1));
        if($data['current_mode'] == 'MOD'){
            //更新处理
            $res = $model::updateAll($data_now, "id=:id",array('id'=> $data['id']));
        }else{
            //新增处理
            $res = Yii::$app->db->createCommand()->insert('j_goods_brand_detail',$data_now)->execute();
        }
        if($res > 0){
            //后台操作日志
            $this->saveLog($this->service,'品牌专题保存' , $data['current_mode']  , \yii\helpers\Json::encode($data_now));
            $this->retJson('处理成功',200);
        }else{
            $this->retJson('处理失败',500);
        }

    }

    /**
     * 取得单个品牌专题信息
     */
    public function actionGetDetailView(){
        try{
            $data = Yii::$app->request->post();

            if(empty($data['id']) || $data['id'] ==''){
                $this->retJson('参数错误！',9003);
            }
            $result = GoodsBrandDetail::findOne(array('id'=>$data['id']));
            $this->retJson(\yii\helpers\Json::encode($result),200);

        }catch(\Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson('系统异常',9003);
        }
    }

    /**
     * 品牌分组首页
     */
    public function actionIndex(){

        //新增
        $where = ['use_flg'=>1];
        $list = GoodsBrand::find()->where($where)->asArray()->all();
        $tag_list = array_unique(array_column($list,'tag'));
        $brand = array();
        foreach($tag_list as $value){
            $brand[]['tag'] = $value;
        }

        foreach($brand as &$value){
            foreach($list as $val){
                if($value['tag'] == $val['tag']){
                    $value['child_list'][] = $val;
                }
            }
        }

       /* //编辑
        $edit_list = GoodsBrand::find()->asArray()->all();
        $tag_edit_list = array_unique(array_column($edit_list,'tag'));
        $brand_list = array();
        foreach($tag_edit_list as $data){
            $brand_list[]['tag'] = $data;
        }

        foreach($brand_list as &$data){
            foreach($edit_list as $val){
                if($data['tag'] == $val['tag']){
                    $data['child_list'][] = $val;
                }
            }
        }
		print_r($brand_list);exit;*/
        //后台操作日志
        $this->saveLog($this->service,'品牌分组' , 'VIEW'  , '');
        return $this->render('index',['tag_group'=>$brand,'tag_group_list'=>$brand]);
    }

    /**
     * 获取品牌组列表
     */
    public function actionGetBrandGroup(){
        $data = Yii::$app->request->post();
        $condition = array();
        if(!empty($data['group_name'])){
            $condition = ['like', 'group_name', $data['group_name']];
        }
        $query = GoodsCategoryBrGroup::find()->where($condition);
        $count = $query->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $query->offset($data['start'])->limit($data['length'])
            ->orderBy(array("$sort_string"=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->all();
        if(empty($list)){
            $list = array();
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 禁用品牌组
     */
    public function actionDisableBrand(){
        $model = new GoodsCategoryBrGroup();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 0;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id=:id",array(':id'=>$data['id']));

        if($res > 0){
            //后台操作日志
            $this->saveLog($this->service,'品牌分组禁用' , 'USEFLG0'  , 'id = ' . $data['id']);
            $this->retJson('禁用成功',200);
        }else{
            $this->retJson('禁用失败',500);
        }
    }

    /**
     * 启用品牌组
     */
    public function actionEnableBrand(){
        $model = new GoodsCategoryBrGroup();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 1;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id=:id",array(':id'=>$data['id']));

        if($res > 0){
            //后台操作日志
            $this->saveLog($this->service,'品牌分组启用' , 'USEFLG1'  , 'id = ' . $data['id']);
            $this->retJson('启用成功',200);
        }else{
            $this->retJson('启用失败',500);
        }
    }

    //添加品牌分组,并将品牌添加到品牌组
    public function actionAddCateBrGroup(){
        $model = new GoodsCategoryBrGroup();

        $brand = GoodsBrand::find()->select('id,brand_name')->asArray()->all();
        $brand_list = array();
        foreach($brand as $value){
            $brand_list[$value['id']]['brand_name'] = $value['brand_name'];
        }

        $data = Yii::$app->request->post();

        $data_now['group_name'] = trim($data['group_name']);
        $data_now['group_alias'] = trim($data['group_alias']);
        $data_now['create_time'] = date('Y-m-d H:i:s',time());
        $data_now['creator'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        $result = tools::arrayHasValue($data,'brand_id') ? $data['brand_id'] : [];
        $transaction = Yii::$app->db->beginTransaction();
        try{
            if (count($result) == 0){
                throw new \Exception('请选择品牌');
            }
            $res = Yii::$app->db->createCommand()->insert('j_goods_category_br_group',$data_now)->execute();
            $result_id = Yii::$app->db->getLastInsertID();
            if(!$res){
                throw new \Exception('操作失败');
            }
            $list = array();
            if (is_array($result) && count($result) > 0)foreach($result as $key=>$value){
                $list[] = [$result_id,$data['group_name'],$data_now['group_alias'],$value,$brand_list[$value]['brand_name'],$model->getCreator(),date('Y-m-d H:i:s',time())];
            }
            $field_name = ['group_id','group_name','group_alias','brand_id','brand_name','creator','create_time'];
            $ret = Yii::$app->db->createCommand()->batchInsert('j_goods_category_br', $field_name, $list)->execute();
            if(!$ret){
                throw new \Exception('操作失败');
            }
            $transaction->commit();
            //后台操作日志
            $this->saveLog($this->service,'品牌分组添加' , 'ADD'  ,  '分组名称：' .$data_now['group_name'] . "\r\n" .  \yii\helpers\Json::encode($list));

            $this->retJson('添加成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            $this->retJson($e->getMessage(),500);
        }
    }

    /**
     * 获取一个品牌组详情
     */
    public function actionGetOneBrandGroup(){
        $data = Yii::$app->request->post();
        $map = ['id'=>$data['id']];
        $result = GoodsCategoryBrGroup::find()->where($map)->asArray()->one();
        $result['brand_id_list'] = '';
        if(!empty($result)){
            $where = ['group_id'=>$result['id']];
            $brand_id = GoodsCategoryBr::find()->where($where)->select('brand_id')->asArray()->all();
            $brand_id_list = array_column($brand_id,'brand_id');
            $result['brand_id_list'] = implode(',',$brand_id_list);
        }

        return \yii\helpers\Json::encode($result);
    }

    /**
     * 修改品牌组
     */
    public function actionUpdateCateBrGroup(){
        $model = new GoodsCategoryBr();
        $data = Yii::$app->request->post();
        if(empty($data['old_brand_id'])){
            $data['old_brand_id'] = array();
        }else{
            $data['old_brand_id'] = explode(',',$data['old_brand_id']);
        }
        $data['brand_id'] = tools::arrayHasValue($data,'brand_id') ? $data['brand_id'] : [];
        $brand = GoodsBrand::find()->select('id,brand_name')->asArray()->all();
        $brand_list = array();
        foreach($brand as $value){
            $brand_list[$value['id']]['brand_name'] = $value['brand_name'];
        }


        //用于增加
        $result_add = array_diff($data['brand_id'],$data['old_brand_id']);

        //用于删除
        $result_del = array_diff($data['old_brand_id'],$data['brand_id']);

        $transaction = Yii::$app->db->beginTransaction();
        try{
            if (count($data['brand_id']) == 0){
                throw new \Exception('编辑失败，请选择品牌');
            }
            $data_now['group_name'] = trim($data['group_name']);
            $data_now['group_alias'] = trim($data['group_alias']);
            $data_now['edit_time'] = date('Y-m-d H:i:s',time());
            $data_now['editor'] = $model->getCreator();
            $data_now['use_flg'] = $data['use_flg'];

            $res = GoodsCategoryBrGroup::updateAll($data_now, " id = ".$data['id']);

            if(!$res){
                throw new \Exception('编辑失败');
            }

            if(!empty($result_add)){
                //添加新的品牌
                $list = array();
                foreach($result_add as $key=>$value){
                    $list[] = [$data['id'],$data_now['group_name'],$data_now['group_alias'],$value,$brand_list[$value]['brand_name'],$model->getCreator(),date('Y-m-d H:i:s',time())];
                }
                $field_name = ['group_id','group_name','group_alias','brand_id','brand_name','creator','create_time'];
                $ret = Yii::$app->db->createCommand()->batchInsert('j_goods_category_br', $field_name, $list)->execute();
                if(!$ret){
                    throw new \Exception('操作失败');
                }
            }
            if(!empty($result_del)){
                //删除旧品牌
                $where = ['group_id'=>$data['id'],'brand_id'=>$result_del];
                $red = $model::deleteAll($where);
                if(!$red){
                    throw new \Exception('操作失败');
                }
            }

            //编辑品牌组名
            $map = ['group_id'=>$data['id'],'brand_id'=>$data['brand_id']];
            $new_data['group_name'] = $data_now['group_name'];
            $model::updateAll($new_data,$map);

            $transaction->commit();
            //后台操作日志
            $this->saveLog($this->service,'品牌分组编辑' , 'MOD'  ,  '分组名称：' .$data_now['group_name'] . "\r\n" .  \yii\helpers\Json::encode($new_data));
            $this->retJson('编辑成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }
}